//
//  RankingViewController.m
//  CoolTennisBall
//
//  Created by Coollang on 2017/7/26.
//  Copyright © 2017年 CoolLang. All rights reserved.
//

#import "RankingMianViewController.h"
#import "CoollangTennisBall-Swift.h"
#import "UIImageView+CM_ShowImage.h"
#import <HMSegmentedControl/HMSegmentedControl.h>
#import <SDWebImage/UIImageView+WebCache.h>
#import "UIView+Frame.h"
#import "RankMainHeadView.h"
#import "RankShotsController.h"
#import "RankAvgScoreController.h"
#import "UserCustomScrollView.h"
#import "MyRankInfoModel.h"
#import "RankUserInfoController.h"
#import "RankUserinfoModel.h"
#import "MBProgressHUD+Add.h"
#import "PhotoActionSheetViewController.h"


#define kRankHeadViewHeight 303
#define kRankHeadViewMaxHeight 373

@interface RankingMianViewController ()<UIScrollViewDelegate,UIImagePickerControllerDelegate, UINavigationControllerDelegate>

@property (weak, nonatomic) IBOutlet UserCustomScrollView *bottomScrollView;
@property (weak, nonatomic) IBOutlet UIScrollView *horizontalScrollview;

// 选择器
@property (weak, nonatomic) IBOutlet UISegmentedControl *navSegmentContol;
@property (weak, nonatomic) IBOutlet HMSegmentedControl *topSegmentControl;
@property (weak, nonatomic) IBOutlet RankMainHeadView *rankHeadView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *rankHeadViewConH;


// 数据
//@property (nonatomic, strong) MyRankInfoModel *myinfomodel;
/**
 我的排名数据
 key:shotsRank:击球排名 avgScoreRank得分排名
 */
@property (nonatomic, strong) NSDictionary <NSString *,MyRankInfoModel *> *myinfoModelDict;

/** 
 不包含前三
  key:shotsRank:击球排名 avgScoreRank得分排名
 */
@property (nonatomic, strong) NSDictionary <NSString *,NSArray *> *dataSourceDict;

//@property (nonatomic, strong) NSArray <RankingModel *> *dataSource;
/**
 前三位
 key:shotsRank:击球排名 avgScoreRank得分排名
 */
@property (nonatomic, strong) NSDictionary <NSString *,NSArray *> *topThreeTankItems;
//@property (nonatomic, strong) NSArray *calculateRankItems;



@end

@implementation RankingMianViewController {
    RankModeType _rankMode;
    RankShotsController *_shotsController;
    RankAvgScoreController *_avgScoreController;
    RankModeType _currentModeType;
    BOOL _isRequestRankInfo; // 是否正在请求用户详情
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initializeBaseUI];
    [self configuerRankheadView];
    [self configureTopSegmentedControl];
    [self addRefresh];
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self.bottomScrollView.mj_header beginRefreshing];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    __weak typeof(self) weakSelf = self;
    if ([segue.identifier isEqualToString:@"ShotsControllerSegue"]) {
        _shotsController = segue.destinationViewController;
//        点赞操作
        [_shotsController setLikeClickHandleBlock:^(RankingModel *rankitem, LikeCallBackBlock calBack){
            [weakSelf likeclickHandle:rankitem.userID oldLiked:rankitem.isLiked callBack:calBack];
        }];
//        显示用户详情
        [_shotsController setShowUserRankInfoVcBlock:^(RankingModel *rankItem,LikeCallBackBlock callBack){
            [weakSelf showUserRankInfo:rankItem likeCallBack:callBack];
        }];
        
    }else if ([segue.identifier isEqualToString:@"AvgScoreControllerSegue"]){
        _avgScoreController = segue.destinationViewController;
        [_avgScoreController setLikeClickHandleBlock:^(RankingModel *rankitem, LikeCallBackBlock calBack){
            [weakSelf likeclickHandle:rankitem.userID oldLiked:rankitem.isLiked callBack:calBack];
        }];
//        显示用户详情
        [_avgScoreController setShowUserRankInfoVcBlock:^(RankingModel *rankItem, LikeCallBackBlock callBack){
            
            [weakSelf showUserRankInfo:rankItem likeCallBack:callBack];
        }];
        
    }
}

- (void)initializeBaseUI {
    _isRequestRankInfo = NO;
    _currentModeType = RankModeTypeSwings;// 设置默认类型
    
    self.navSegmentContol.width = kAutoWid(200);
    self.navSegmentContol.height = kAutoHei(28);
    CGFloat navfontSize = 16;
    if ([NSBundle currentLangeuage] == kLanguageFrennch){
        navfontSize = 12;
    }
    [self.navSegmentContol setTitleTextAttributes:@{NSFontAttributeName:[UIFont fontWithDescriptor:FontDescriptorMedium(navfontSize) size:0.0]} forState:UIControlStateNormal];
   
    
    [self.navSegmentContol setTitle:NSLocalizedString(@"Weekly Ranking", @"周排行") forSegmentAtIndex:0];
    [self.navSegmentContol setTitle:NSLocalizedString(@"Monthly Ranking", @"月排行") forSegmentAtIndex:1];
    
    [self.navSegmentContol addTarget:self action:@selector(navSegmentContolValueChange:) forControlEvents:UIControlEventValueChanged];
}

- (void)navSegmentContolValueChange:(UISegmentedControl *)segmentControl {
    [self.bottomScrollView.mj_header beginRefreshing];
}

- (void)configuerRankheadView {
    __weak typeof(self) weakSelf = self;
    
//    给前三位点赞
    [self.rankHeadView setTopThreeLikeHandelBlock:^(RankingModel *rankItem,NSInteger index,LikeCallBackBlock callBack){
        
        [weakSelf likeclickHandle:rankItem.userID oldLiked:rankItem.isLiked callBack:^(BOOL success) {
//            if (success){
//                if(weakSelf.calculateRankItems.count > index){
//                    // 此处不完善
//                    [weakSelf.calculateRankItems[index] setIsLiked:!(rankItem.isLiked)];
//                }
//            }
            callBack(success);
        }];
    }];
    
//    展开谁给我点赞
    [self.rankHeadView setLookMyLikesHanldeblock:^(BOOL open){
        [weakSelf showMyUserLikelist:open];
    }];
    
//    查看前三位的用户详情
    [self.rankHeadView setShowUserRankInfoVcBlock:^(RankingModel *rankItem,LikeCallBackBlock callBack){
        
        [weakSelf showUserRankInfo:rankItem likeCallBack:callBack];
    }];
    
//    上传头像
    [self.rankHeadView setUploadHeadIconImageBlock:^{
        [weakSelf uploadHeadIconImage];
    }];
}

- (void)showMyUserLikelist:(BOOL)open {
    if(open == self.rankHeadViewConH.constant > kRankHeadViewHeight){
        return;
    }
    self.rankHeadViewConH.constant = open ? kRankHeadViewMaxHeight:kRankHeadViewHeight;
    
    [UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
        [self.rankHeadView layoutIfNeeded];
        self.rankHeadView.myReclycelButton.alpha = open;
        self.rankHeadView.myLikeUserListLabel.alpha = open;
    } completion:^(BOOL finished) {
        self.rankHeadView.myReclycelButton.hidden = !open;
        self.rankHeadView.myLikeUserListLabel.hidden = !open;
    }];
}

- (void)configureTopSegmentedControl {
    
    self.topSegmentControl.sectionTitles =@[NSLocalizedString(@"Shots", nil), NSLocalizedString(@"Avg Score", nil)];
    
    __weak typeof(self) weakSelf = self;
    [self.topSegmentControl setIndexChangeBlock:^(NSInteger index) {
        NSLog(@"Selected index %ld (via block)", (long)index);
        weakSelf.horizontalScrollview.contentOffset = CGPointMake(kYFScreenWidth * weakSelf.topSegmentControl.selectedSegmentIndex, 0);
        _currentModeType = (index + 1);
        [self updateConfigureUI];
//        [weakSelf.bottomScrollView.mj_header beginRefreshing];
    }];
    
    self.topSegmentControl.selectionIndicatorHeight = 3.0f;
    self.topSegmentControl.backgroundColor = [UIColor clearColor];
    
    CGFloat fontSize = [NSBundle currentLanguageIsChinese] ? 14.0f : 14.0f;
    self.topSegmentControl.selectedTitleTextAttributes = @{NSForegroundColorAttributeName : kSelectedColor, NSFontAttributeName: MYFONT(fontSize)};
    self.topSegmentControl.titleTextAttributes =@{NSForegroundColorAttributeName : [UIColor colorWithHex:0x666666], NSFontAttributeName: MYFONT(fontSize)};
    
    self.topSegmentControl.selectionIndicatorColor = kSelectedColor;
    self.topSegmentControl.selectionIndicatorBoxOpacity = 0.8;
    self.topSegmentControl.selectionStyle = HMSegmentedControlSelectionStyleTextWidthStripe;
    self.topSegmentControl.selectedSegmentIndex = 0;
    self.topSegmentControl.selectionIndicatorLocation = HMSegmentedControlSelectionIndicatorLocationDown;
    self.topSegmentControl.shouldAnimateUserSelection = YES;
}

- (void)addRefresh {
    [self.bottomScrollView addLegendHeaderWithShowTime:NO RefreshingBlock:^{
         [self requestData];
    }];
}

- (void)updateConfigureUI {
    
     //[self.rankHeadView updateRankHeadView:self.calculateRankItems withMyranInfoModel:self.myinfomodel rankModelType:_currentModeType];
    
    _shotsController.dataSource = self.dataSourceDict[@"shotsRank"];
    _avgScoreController.dataSource = self.dataSourceDict[@"avgScoreRank"];
    
    NSString *key = _currentModeType == RankModeTypeSwings ? @"shotsRank":@"avgScoreRank";
    
    [self.rankHeadView updateRankHeadView:self.topThreeTankItems[key] withMyranInfoModel:self.myinfoModelDict[key] rankModelType:_currentModeType];
    
//    switch (_currentModeType) {
//        case RankModeTypeSwings:{
//            key = @"shotsRank";
////            _shotsController.dataSource = self.dataSource;
//        }
//            break;
//        case RankModeTypeAvgScore:{
//            key = @"avgScoreRank";
////            _avgScoreController.dataSource = self.dataSource;
//        }
//            break;
//        default:
//            break;
//    }
}

- (void)requestData {
    
    // 0为月排名,1为累计排名,2为周排名
    NSString *classStr = self.navSegmentContol.selectedSegmentIndex == 0 ? @"2":@"0";
    
    YFRankApi *rankShotsApi = [YFRankApi requestRankinglistWithRankType:@"1" timePeriod:classStr];
    
    YFRankApi *rankAvgScoreApi = [YFRankApi requestRankinglistWithRankType:@"2" timePeriod:classStr];
    
    [[YFNetworkingService sharedInstance] sendBatch:@[rankShotsApi,rankAvgScoreApi] callback:^(BOOL success, id result, NSError *error) {
        [self.bottomScrollView.mj_header endRefreshing];
        if (success){
            self.myinfoModelDict = @{@"shotsRank":rankShotsApi.myRankInfoItem,
                                     @"avgScoreRank":rankAvgScoreApi.myRankInfoItem};
            NSArray *shotArr = [self calculateRankItemsFromOrignalRankItems:rankShotsApi.rankItems];
            
            NSArray *avgscoreArr = [self calculateRankItemsFromOrignalRankItems:rankAvgScoreApi.rankItems];
            
            self.dataSourceDict = @{@"shotsRank":shotArr.lastObject,
                                    @"avgScoreRank":avgscoreArr.lastObject,};
            
            self.topThreeTankItems = @{@"shotsRank":shotArr.firstObject,@"avgScoreRank":avgscoreArr.firstObject};
            [self updateConfigureUI];
        }
    }];
}

// 查看用户排行榜详情
- (void)showUserRankInfo:(RankingModel *)rankItem likeCallBack:(LikeCallBackBlock)likeClikeHandel {
    
    if (_isRequestRankInfo){
        return;
    }
    YFRankApi *userInfoApi = [YFRankApi requestOtherRankingType:kRankGetUserinfo andUserId:rankItem.userID];
    _isRequestRankInfo = YES;
    
    [[YFNetworkingService sharedInstance] sendRequest:userInfoApi callback:^(BOOL success, id result, NSError *error) {
        _isRequestRankInfo = NO;
        if (success) {
            RankUserinfoModel *infoModel = [RankUserinfoModel rankUserInfoModelWithDict:userInfoApi.responseInfo];
            RankUserInfoController *infoVc = [RankUserInfoController rankUserInfoControllerWithRankInfoModel:infoModel];
            infoVc.isliked = rankItem.isLiked;
            [infoVc presentInParentViewController:self.tabBarController animationType:DetailViewControllerPresentAnimationTypeFadeUp];
            
            [infoVc setLikeButtonClickBlock:^(BOOL oldLiked,LikeCallBackBlock callback){
                [self likeclickHandle:rankItem.userID oldLiked:oldLiked callBack:^(BOOL success) {
                    if (likeClikeHandel){
                        likeClikeHandel(success);
                    }
                    if (callback){
                        callback(success);
                    }
                }];
            }];
        }else {
            [MBProgressHUD showFailHudInView:self.view message:NSLocalizedString(@"Network anomaly", nil) afterDelay:1.2];
        }
    }];
    
}

// 点赞操作
- (void)likeclickHandle:(NSString *)userId oldLiked:(BOOL)oldLike callBack:(LikeCallBackBlock)callback {
    YFRankApi *api = [YFRankApi requestOtherRankingType:(oldLike ? kRankDellike:kRankAddlike) andUserId:userId];
    [[YFNetworkingService sharedInstance] sendRequest:api callback:^(BOOL success, id result, NSError *error) {
         callback(success);
    }];
}

- (NSArray *)calculateRankItemsFromOrignalRankItems:(NSArray *)rankItems
{
    NSMutableArray *calculateRankItems = [@[] mutableCopy];
    NSMutableArray *topRankItems = [@[] mutableCopy];
    for (NSInteger index = 0; index < [rankItems count]; index++) {
        if (index < 3) {
            [topRankItems addObject:rankItems[index]];
        } else {
            [calculateRankItems addObject:rankItems[index]];
        }
    }
//    self.calculateRankItems = topRankItems.copy;
//    self.dataSource = calculateRankItems.copy;
    return  @[topRankItems.copy,calculateRankItems.copy];
}

#pragma mark - scrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if ([scrollView isEqual:self.horizontalScrollview]){
        NSInteger page = (scrollView.contentOffset.x + kYFScreenWidth * 0.5)/ kYFScreenWidth;
        self.topSegmentControl.selectedSegmentIndex = page;
    }else {
        [self showMyUserLikelist:NO];
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if ([scrollView isEqual:self.horizontalScrollview]){
        NSInteger page = scrollView.contentOffset.x / kYFScreenWidth;
        self.topSegmentControl.selectedSegmentIndex = page;
        _currentModeType = (self.topSegmentControl.selectedSegmentIndex + 1);
//        [self.bottomScrollView.mj_header beginRefreshing];
    }else {
        
    }
}


#pragma mark - 上传头像
- (IBAction)uploadHeadIconImage {
     __weak typeof(self) weakSelf = self;
    [PhotoActionSheetViewController showInParentViewController:self.tabBarController animationType:DetailViewControllerPresentAnimationTypeUp actionBlock:^(kTapActionButtonType btnType) {
        if (btnType == kTapAlbumButton) {
             [weakSelf takePhotoByPhotos];
        }else if(btnType == kTapCameraButton){
            [weakSelf takePhotoByCamera];
        }
    }];
}
#pragma mark - <从手机中选择图片>

- (void)takePhotoByCamera{
    if(![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        [MBProgressHUD showTextHUDWithMessage:NSLocalizedString(@"Can't get camera or photo information", nil) inView:self.view];
        return;
    }
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    picker.delegate = self;
    [self presentViewController:picker animated:YES completion:nil];
}

- (void)takePhotoByPhotos{
    if(![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        [MBProgressHUD showTextHUDWithMessage:NSLocalizedString(@"Can't get camera or photo information", nil) inView:self.view];
        return;
    }
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.delegate = self;
    [self presentViewController:picker animated:YES completion:nil];
}

#pragma mark - UIImagePickerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    UIImage *image = info[UIImagePickerControllerOriginalImage];
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [YFUserApi uploadImageWithRequestType:kUserUploadHeadImage withImage:image complete:^(NSError *error, NSString *imageUrl) {
        [hud hideAnimated:YES];
        if (error == nil) {
            [self.rankHeadView updateHeadIconWithImage:image];
            [[RLMRealm defaultRealm] beginWriteTransaction];
            [User getLastUser].userInforItem.headIconPath = imageUrl;
            [[RLMRealm defaultRealm] commitWriteTransaction];
            [self.bottomScrollView.mj_header beginRefreshing];
        }
    }];
    
    [picker dismissViewControllerAnimated:YES completion:nil];
}


- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:NO];
}

@end
